/*
 * @Description: 自定义参数table表格组件
 * @Author: gn
 * @Date: 2023-12-12 19:23:06
 * @LastEditors: gn
 * @LastEditTime: 2023-12-14 11:29:58
 */
import React, { useState, memo, useContext, useEffect } from 'react';
import { Table, Input } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import dmContext from './dmContext';
import { deepCopy } from '@/routes/Dm/customParamers/utils';
import PubSub from 'pubsub-js';

// 表格组件
const TableEle = memo(props => {
  // const [inputs, setInputs] = useState([{}]);
  const [tableData, setTableData] = useState([]);
  // let tableData = [];
  let emitFunc = '';
  let useOptions = false;

  const { datasource, options, usedata, selectData } = props;

  PubSub.subscribe('renderData', (name, data) => {
    console.log(
      '%c [ renderData ]-27',
      'font-size:13px; background:pink; color:#bf2c9f;',
      name,
      data
    );
    setTableData(data.columns_data);
  });

  useEffect(() => {
    setTableData(usedata);
  }, [usedata]);

  // usedata && (tableData = usedata);
  options && (useOptions = options);

  if (datasource !== 'props') {
    const { columns_data, setParamsValue, tablColDel } = useContext(dmContext);

    console.log(
      '%c [ columns_data ]-42',
      'font-size:13px; background:pink; color:#bf2c9f;',
      columns_data
    );
    // tableData = columns_data || selectData;
    emitFunc = setParamsValue;
    useOptions = !!tablColDel;
  }

  const optionsObj = {
    title: '操作',
    dataIndex: 'options',
    align: 'center',
    render: (text, record, index) => <DeleteOutlined />,
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'ordinal',
      align: 'center',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '参数',
      dataIndex: 'enname',
      align: 'center',
    },
    {
      title: '对应值',
      dataIndex: 'paramValue',
      align: 'center',
      render: (text, record, index) => {
        record.paramValue = '';
        return (
          <Input
            key={record.enname}
            // value={inputs[index].paramValue}
            size="small"
            onChange={event => handleInputChange(record, event, index)}
            placeholder="请填写对应值"
          />
        );
      },
    },
  ];

  // 需要操作按钮
  useOptions && columns.push(optionsObj);

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const handleInputChange = (record, event, index) => {
    // setInputs([...inputs.slice(0, index), {paramValue: event.target.value}, ...inputs.slice(index + 1)]);
    emitFunc && emitFunc(deepCopy(record), event.target.value, index);
  };

  return (
    <Table
      columns={columns}
      dataSource={tableData}
      bordered
      // loading={true}
      size="small"
      rowKey={i => i.enname}
    />
  );
});

export default TableEle;
